package cn.iocoder.yudao.module.erp.service.purchase;

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.supplier.ErpSupplierPageReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.supplier.ErpSupplierRespVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.supplier.ErpSupplierSaveReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.purchase.vo.supplier.ErpWhiteSupplierSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.purchase.ErpSupplierDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.relationship.RelationshipDO;
import cn.iocoder.yudao.module.erp.dal.mysql.purchase.ErpSupplierMapper;
import cn.iocoder.yudao.module.erp.dal.mysql.relationship.RelationshipMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.SUPPLIER_NOT_ENABLE;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.SUPPLIER_NOT_EXISTS;

/**
 * ERP 供应商 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpSupplierServiceImpl implements ErpSupplierService {

    @Resource
    private ErpSupplierMapper supplierMapper;
    @Resource
    private RelationshipMapper relationshipMapper;

    @Override
    public Long createSupplier(ErpSupplierSaveReqVO createReqVO) {
        ErpSupplierDO supplier = BeanUtils.toBean(createReqVO, ErpSupplierDO.class);
        supplierMapper.insert(supplier);
        return supplier.getId();
    }

    @Override
    public void updateSupplier(ErpSupplierSaveReqVO updateReqVO) {
        // 校验存在
        validateSupplierExists(updateReqVO.getId());
        // 更新
        ErpSupplierDO updateObj = BeanUtils.toBean(updateReqVO, ErpSupplierDO.class);
        supplierMapper.updateById(updateObj);
    }

    @Override
    public void deleteSupplier(Long id) {
        // 校验存在
        validateSupplierExists(id);
        // 删除
        supplierMapper.deleteById(id);
    }

    private void validateSupplierExists(Long id) {
        if (supplierMapper.selectById(id) == null) {
            throw exception(SUPPLIER_NOT_EXISTS);
        }
    }

    @Override
    public ErpSupplierDO getSupplier(Long id) {
        return supplierMapper.selectById(id);
    }

    @Override
    public ErpSupplierDO validateSupplier(Long id) {
        ErpSupplierDO supplier = supplierMapper.selectById(id);
        if (supplier == null) {
            throw exception(SUPPLIER_NOT_EXISTS);
        }
        if (CommonStatusEnum.isDisable(supplier.getStatus())) {
            throw exception(SUPPLIER_NOT_ENABLE, supplier.getName());
        }
        return supplier;
    }

    @Override
    public List<ErpSupplierDO> getSupplierList(Collection<Long> ids) {
        return supplierMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<ErpSupplierDO> getSupplierPages(ErpSupplierPageReqVO pageReqVO) {
        PageResult<ErpSupplierDO> es =  supplierMapper.selectPage(pageReqVO);
        List<ErpSupplierRespVO> dp =  supplierMapper.selectRel(pageReqVO.getProductId());
        // 创建一个Map来快速查找dp中的供应商
        Map<Long, ErpSupplierRespVO> dpMap = new HashMap<>();
        for (ErpSupplierRespVO item : dp) {
            dpMap.put(Long.valueOf(item.getSupplierId()), item);
        }
        // 遍历es集合，并尝试更新每个供应商的信息
        for (ErpSupplierDO supplier : es.getList()) {
            Long supplierId = supplier.getId();
            ErpSupplierRespVO relatedSupplier = dpMap.get(supplierId);
            if (relatedSupplier != null) {
                // 如果找到了匹配的供应商，则更新信息
                supplier.setSort(relatedSupplier.getSort());
                supplier.setMinOrderQuantity(relatedSupplier.getMinOrderQuantity());
            }
            // 注意：如果没有找到匹配的供应商，则不更新，保持原样
        }
        return es;
    }

    @Override
    public PageResult<ErpSupplierDO> getSupplierPage(ErpSupplierPageReqVO pageReqVO) {
        int page = (pageReqVO.getPageNo()-1)*pageReqVO.getPageSize();
        pageReqVO.setPageNo(page);
        List<ErpSupplierDO> es =  supplierMapper.selectPageList(pageReqVO);
        int total = supplierMapper.total(pageReqVO);
        List<ErpSupplierRespVO> dp =  supplierMapper.selectRel(pageReqVO.getProductId());
        PageResult<ErpSupplierDO> result =new PageResult<>();
        // 创建一个Map来快速查找dp中的供应商
        Map<Long, ErpSupplierRespVO> dpMap = new HashMap<>();
        for (ErpSupplierRespVO item : dp) {
            dpMap.put(Long.valueOf(item.getSupplierId()), item);
        }
        // 遍历es集合，并尝试更新每个供应商的信息
        for (ErpSupplierDO supplier : es) {
            Long supplierId = supplier.getId();
            ErpSupplierRespVO relatedSupplier = dpMap.get(supplierId);
            if (relatedSupplier != null) {
                // 如果找到了匹配的供应商，则更新信息
                supplier.setSort(relatedSupplier.getSort());
                supplier.setMinOrderQuantity(relatedSupplier.getMinOrderQuantity());
            }
            // 注意：如果没有找到匹配的供应商，则不更新，保持原样
        }
        result.setList(es);
        result.setTotal((long) total);
        return result;
    }

    @Override
    public PageResult<ErpSupplierDO> getSupplierRegisterPage(ErpSupplierPageReqVO pageReqVO) {
        return supplierMapper.selectRegisterPage(pageReqVO);
    }

    @Override
    public PageResult<ErpSupplierDO> getSupplierRegisterVerifyPage(ErpSupplierPageReqVO pageReqVO) {
        return supplierMapper.selectRegisterVerifyPage(pageReqVO);
    }

    @Override
    public List<ErpSupplierDO> getSupplierListByStatus(Integer status) {
        return supplierMapper.selectListByStatus(status);
    }
    /**
     * 产品名称筛选框查询方法
     * @param status
     * @param params
     * @return
     */
    @Override
    public List<ErpProductRespVO> getSupplierLists(Integer status, String params) {
        //参数拼接%用于模糊查询
        String like ="%"+params+"%";
        return supplierMapper.selectLists(status,like);
    }

    @Override
    public List<ErpSupplierDO> getSupplierByProductId(Long productId) {
        List<RelationshipDO> relationshipDOS = relationshipMapper.selectByProductId(productId);
        List<Long> ids = relationshipDOS.stream().map(RelationshipDO::getSupplierId).collect(Collectors.toList());
        List<ErpSupplierDO> RelationshipDO = supplierMapper.selectListByIds(ids);
        return RelationshipDO;
    }

    @Override
    public Long whiteCreateSupplier(ErpWhiteSupplierSaveReqVO createReqVO) {
        createReqVO.setStatus(CommonStatusEnum.DISABLE.getStatus());
        createReqVO.setSort(0);
        createReqVO.setVerifyAuditContent("审核中");
        ErpSupplierDO supplier = BeanUtils.toBean(createReqVO, ErpSupplierDO.class);
        supplierMapper.insert(supplier);
        return supplier.getId();
    }

}